<template>
  <div class="trainingUsers" :style="{ 'height': $store.oj.systemParams.screenHeight * 0.80 + 'px' }">
    <div class="t-header">
      <div class="t-h-title"> <i class="iconfont icon-tuanduishezhi"></i>训练用户列表</div>
    </div>
    <div class="t-search">
      <n-input class="t-s-input" placeholder="搜索训练" round size="small" v-model:value="searchVal">
        <template #suffix>
          <i class="iconfont icon-sousuo" @click=" searchParams.username = searchVal"></i>
        </template>
      </n-input>
      <n-button class="t-s-btn" size="small" round type="success" @click="isShowAppend = true">
        <i class="iconfont icon-tianjia"></i>
        添加用户
      </n-button>
      <transition>
        <n-button class="t-s-btn" size="small" round type="error" v-show="selectedUser.length > 0"
          @click="delProtectUsers(selectedUser)">
          <i class="iconfont icon-shanchu"></i>
          批量删除
        </n-button>
      </transition>
    </div>
    <div class="t-table">
      <el-table :data="userList.records" size="small" stripe class="table" border @selection-change="selectionchange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scoped">
            <div>
              <n-button size="tiny" type="error" @click="delProtectUsers([scoped.row.id])">
                <i class="iconfont icon-shanchu"></i>
              </n-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <el-pagination class="pagination" :page-sizes="[20, 50, 99]" background small layout="prev, pager, next,sizes"
        :total="Number(userList.total)" v-model:current-page="searchParams.pageNum"
        v-model:page-size="searchParams.pageSize" />
    </div>

    <n-modal v-model:show="isShowAppend">
      <n-card :bordered="false" role="dialog" aria-modal="true" class="card">
        <h2 class="bigtitle">添加用户</h2>
        <div class="inputUser">
          <n-input class="ipt" placeholder="输入用户名" size="small" v-model:value="userName"></n-input>
          <n-button class="btn" size="small" round type="success" @click="appendUser">
            <i class="iconfont icon-tianjia"></i>
            加入名单
          </n-button>
          <n-button class="btn2" size="small" round type="success" @click="downTemplate()">
            <i class="iconfont icon-xiazai1"></i>
            下载模板
          </n-button>
        </div>
        <el-upload class="upload-demo" :show-file-list="false" :auto-upload='false' :limit="1" action="#"
          :on-change="fileChange" accept=".xls,.xlsx" drag>
          <i class="iconfont icon-icon_update bigIcon"></i>
        </el-upload>
        <el-table class="table" :data="proTectTrainData.userList" stripe size="small">
          <el-table-column type="index" label="序号" align="center" width="100"></el-table-column>
          <el-table-column prop="name" label="用户名" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scoped">
              <div>
                <n-button size="tiny" type="error" @click="delUser(scoped.row.name)">
                  <i class="iconfont icon-shanchu"></i>
                </n-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="footer">
          <n-button size="small" type="success" @click="appendProtectTrainingUser">保存</n-button>
        </div>
      </n-card>
    </n-modal>
  </div>
</template>
<script setup>
import { getProtectUsersAPI, appendProtectTrainingUserAPI, delProtectUsersAPI, getTrainUserTempAPI } from "@/api/adminAPI/adminAPI"
import { onMounted, reactive, watch, ref } from "vue"
import { useRoute } from "vue-router"
import { ElMessage } from 'element-plus'
import useStore from "@/store"
import * as XLSX from 'xlsx'
import { ElNotification } from 'element-plus'
const route = useRoute()
const store = useStore()

onMounted(() => {
  searchParams.tid = route.params.tid
  proTectTrainData.tid = route.params.tid
})

const searchParams = reactive({
  pageNum: 1,
  pageSize: 20,
  username: '',
  tid: ''
})
const userList = reactive({
  records: [],
  total: 10
})
const getProtectUsers = async () => {
  await getProtectUsersAPI(searchParams).then(res => {
    if (res.data.code === 200) {
      userList.records = res.data.data.records
    }
  }).catch(err => {
    console.log(err)
  })
}
watch(searchParams, () => {
  getProtectUsers()
})

const searchVal = ref('')
watch(searchVal, (newV) => {
  if (newV.length == 0)
    getProtectUsers()
})



//增加保护训练用户
const isShowAppend = ref(false)
const proTectTrainData = reactive({
  tid: '',
  userList: []
})
const appendProtectTrainingUser = async () => {
  const a = {
    tid: proTectTrainData.tid,
    userList: []
  }
  a.userList = proTectTrainData.userList.map(ele => {
    return ele.name
  })
  await appendProtectTrainingUserAPI(a).then(res => {
    if (res.data.code === 200) {
      if (res.data.data.failSaveList.length == 0) {
        ElNotification({
          title: '成功',
          message: '全部用户添加成功',
          type: 'success',
          duration: 5000
        })
      } else if (res.data.data.successSaveList.length == 0) {
        ElNotification({
          title: '添加失败名单',
          message: res.data.data.failSaveList,
          type: 'error',
          duration: res.data.data.failSaveList.length < 10 ? res.data.data.failSaveList.length * 1000 : 10000

        })
      } else {
        ElNotification({
          title: '部分添加失败名单',
          message: + res.data.data.failSaveList,
          type: 'warning',
          duration: res.data.data.failSaveList.length < 10 ? res.data.data.failSaveList.length * 1000 : 10000
        })
      }
      proTectTrainData.userList = []
      getProtectUsers()
    }
  }).catch(err => {
    console.log(err)
  })
}
const isShowResult = ref(false)

//处理excel(解析)
const fileChange = (uploadFile, uploadFiles) => {
  const file = uploadFile.raw
  if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    ElMessage.error('请上传xls/xlsx格式文件')
    return false
  }
  // 读取表格
  const fileReader = new FileReader()
  fileReader.onload = ev => {
    const workbook = XLSX.read(ev.target.result, {
      type: "binary"
    })
    const wsname = workbook.SheetNames[0]
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
    proTectTrainData.userList = [...proTectTrainData.userList, ...ws]
  }
  fileReader.readAsBinaryString(file)
}
//删除保护训练用户
const delProtectUsers = async (ids) => {
  await delProtectUsersAPI(ids).then(res => {
    if (res.data.code === 200) {
      getProtectUsers()
      ElMessage.success(res.data.msg)
    }
  }).catch(err => {
    console.log(err)
  })
}
//选中的用户数据
const selectedUser = ref([])
const selectionchange = (selection) => {
  selectedUser.value = selection.map((ele) => {
    return ele.id
  })
}
const delUser = (name) => {
  proTectTrainData.userList.forEach((ele, index) => {
    if (ele.name == name) {
      proTectTrainData.userList.splice(index, 1)
      return
    }
  })
}

//添加单个用户
const userName = ref('')
const appendUser = () => {
  if (userName.value.length == 0) {
    ElMessage.error("请输入用户名")
    return
  }
  proTectTrainData.userList.push({
    name: userName.value,
    id: '--'
  })
  ElMessage.success("已添加")
  userName.value = ''
}

//下载模板
const getTemplatetimer = ref(0)
const downTemplate = async () => {
  const now = Date.now()
  if (now - getTemplatetimer.value < 30000) {
    ElMessage.warning("请勿频繁下载")
    return
  }
  getTemplatetimer.value = now
  await getTrainUserTempAPI().then(res => {
    const url = window.URL.createObjectURL(new Blob([res.data]), {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'trainingUserTemplate.xlsx') // 设置文件名
    document.body.appendChild(link)
    link.click()
  }).catch(err => {
    console.log(err)
  })
}
</script>
<style lang="less" scoped>
.trainingUsers {
  margin: auto;
  width: 96%;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 12px 12px 50px #d9d9d9,
    -12px -12px 50px #ffffff;
  display: flex;
  flex-direction: column;

  .t-header {
    display: flex;

    .t-h-title {
      height: 30px;
      line-height: 30px;
      font-size: 20px;
      font-weight: 600;
      color: #555;
      display: flex;
      text-align: center;

      .iconfont {
        margin: auto 0;
        font-weight: 700;
        font-size: 28px;
        height: 30px;
      }
    }
  }

  .t-search {
    display: flex;
    height: 30px;
    line-height: 30px;
    margin: 20px 0 0 0;
    padding-bottom: 10px;
    border-bottom: 2px solid @lineColor;

    .t-s-input {
      height: 30px;
      line-height: 30px;
      width: 20%;
    }

    .t-s-btn {
      margin: auto 0 auto 20px;
    }
  }

  .t-table {
    width: 100%;
    margin: 10px auto 0 auto;

  }

  .footer {
    margin: auto 0 0 0;
    padding-top: 5px;
    display: flex;
    justify-content: center;
  }
}

::v-deep(.n-card__content) {
  padding: 10px !important;
}

.card {
  border-radius: 20px;
  overflow: hidden;
  height: 80vh;
  width: 80vw;



  .bigtitle {
    border-bottom: 1px solid @bgColor;
    padding-bottom: 10px;
  }

  .inputUser {
    display: flex;
    margin: 10px 0;

    .ipt {
      width: 15%;
    }

    .btn {
      margin: auto 10px;
    }

    .btn2 {
      margin: auto 10px auto auto;
    }
  }

  .upload-demo {}

  .table {
    height: 45vh;
  }

  .footer {
    display: flex;
    justify-content: center;
  }

}

.card2 {
  width: 30vw;
  height: 50vh;
  border-radius: 20px;
  overflow: hidden;

  .bigtitle {
    border-bottom: 1px solid @bgColor;
    color: #555;
    text-align: center;
  }
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.3s ease-in-out;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>